const express = require('express')
const cors = require('cors')
const path =require('path')
const multiparty = require('multiparty')
const fse = require('fs-extra')
const bodyParser = require('body-parser')

const app = express()

app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: false }))
// 所有上传的文件存放到该目录下
const UPLOAD_DIR = path.resolve(__dirname, 'uploads')

// 处理上传的分片
app.post('/upload', (req, res) => {
  const form = new multiparty.Form()
  console.log(req.body)
  // res.send({
  //   msg:'666'
  // })
  // return
  form.parse(req, async function (err, fields, files) {

    if (err) {
      res.status(401).json({
        ok: false,
        msg: '上传失败',
      })
      return
    }
    
    const chunkHash = fields['chunkHash'][0]
    const fileName = fields['fileName'][0]
    const fileHash = fields['fileHash'][0]

    // 存储切片的临时文件夹
    const chunkDir = path.resolve(UPLOAD_DIR, fileHash)

    // 切片目录不存在，则创建切片目录
    if (!fse.existsSync(chunkDir)) {
      await fse.mkdirs(chunkDir)
    }

    const oldPath = files.chunk[0].path
    // 把文件切片移动到我们的切片文件夹中
    await fse.move(oldPath, path.resolve(chunkDir, chunkHash))

    res.status(200).json({
      ok: true,
      msg: 'received file chunk',
    })
  })
})
app.get('/add',(req,res)=>{
  res.send({
    msg:'666'
  })
})

app.listen(3001, () => {
  console.log(`serve running at http://127.0.0.1:3001`)
})
